<script setup lang="ts">
import type {Case} from "@/interface/interface";
import {useTurnStore} from "@/stores/turn.ts";
import {
  Document,
  EditPen,
  Files,
  InfoFilled,
  Location,
  RefreshLeft,
  Search,
  Share,
  Timer
} from '@element-plus/icons-vue'
import {computed, nextTick, onMounted, ref, watch} from "vue";

const store = useTurnStore();
const tableData = ref<Case[]>([])
const loading = ref(false)
const turn = computed(() => {
  return store.turnData === 'Law_case'
})

// 缓存过滤后的数据
const filteredData = ref<Case[]>([])
const currentPage = ref(1)
const pageSize = ref(25) // 分页大小
const tableRef = ref()
const over = ref(false)
const getData = computed(() => {
  return store.provinceEvent.province !== "" && store.provinceEvent.event !== "" && tableData.value.length !== 0
})
let searchTimeout: number

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(0, end)
})

const handleClick = (Case: Case) => {
  store.dialogVisible = Case;
  store.showOfDialog = true;
}

// 优化数据过滤逻辑
const filterData = () => {
  if (store.provinceEvent.province === "" || store.provinceEvent.event === "") {
    filteredData.value = []
    return
  }

  const pro = store.allProvinceData.find((item) => item.name === store.provinceEvent.province);
  if (!pro) {
    filteredData.value = []
    return
  }
  filteredData.value = pro.data.filter((item) => item.caseType === store.provinceEvent.event);
  currentPage.value = 1 // 重置到第一页
}

const handleClick1 = async () => {
  loading.value = true;
  await new Promise(resolve => setTimeout(resolve, 1000))
  try {
    await nextTick()
    filterData()
    tableData.value = currentPageData.value
  } finally {
    loading.value = false;
  }
}

const handleShowRelatedNodeClick=(selectedCase:Case)=>{
  store.appendChosenCaseIds(selectedCase.id);
}

// 防抖搜索
const debouncedSearch = (searchText: string) => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }

  searchTimeout = setTimeout(() => {
    if (searchText === "") {
      filterData()
      tableData.value = currentPageData.value
      return
    }
    // 优化搜索逻辑，使用更高效的方法
    const searchLower = searchText.toLowerCase()
    filteredData.value = filteredData.value.filter((item) => {
      return item.caseName.toLowerCase().includes(searchLower) ||
        item.party.toLowerCase().includes(searchLower) ||
        item.legalBasis.toLowerCase().includes(searchLower) ||
        item.fullText.toLowerCase().includes(searchLower) ||
        item.court.toLowerCase().includes(searchLower)
    })
    currentPage.value = 1
    tableData.value = currentPageData.value
  }, 300) // 300ms 防抖延迟
}

const searchData = () => {
  debouncedSearch(store.searchText)
}

// 分页处理
const handleCurrentChange = () => {
  currentPage.value += 1
  tableData.value = currentPageData.value
}

const handleScroll = ({scrollTop}) => {
  if (scrollTop === (currentPage.value-1)*25*41 + 922) {
    if(tableData.value.length === filteredData.value.length){
      over.value = true
    } else {
      over.value = false
      handleCurrentChange()
    }
  }
}

const handleDblClick = () => {
  if(store.turnData === "Law_case"){
    store.turnData = ""
  }else{
    store.turnData = "Law_case"
  }
}

onMounted(() => {
  // 合并多个watch为一个，减少重复执行
  watch([() => store.provinceEvent.event, () => store.provinceEvent.province], ([newEvent, newProvince]) => {
    if (newEvent !== "" && newProvince !== ""){
      handleClick1()
      store.searchText = ""
    }
  })

  watch(() => store.searchText, () => {
    searchData()
  })
})
</script>

<template>
  <div class="lawCase" :class="{active: turn}">
    <h4 style="color: white;text-align: center; padding-top: 5px;margin: 0;" >
      {{ tableData.length > 0
        ? `${store.provinceEvent.province}: ${store.provinceEvent.event}列表详情`
        : '案件列表详情' }}
      <span @click="handleDblClick" style="padding-top: 10px; transition: all 1s ease;
cursor: pointer;">
        <el-icon><ArrowLeft /></el-icon><el-icon><ArrowRight /></el-icon>
      </span>
    </h4>
    <el-divider style="width: 98%;margin: 10px 0;"/>
    <div class="select">
      <el-select v-model="store.provinceEvent.province" clearable placeholder="选择想要查询的省份"
                 style="width: 300px">
        <el-option
          v-for="item in store.allProvinceData.map((item1) => ({ label: item1.name, value: item1.name }))"
          :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-select v-model="store.provinceEvent.event" clearable placeholder="选择想要查询的事件类型"
                 style="width: 300px; margin-left: 10px" @change="handleClick1">
        <el-option v-for="item in store.keyOfCauseOfAction" :key="item" :label="item"
                   :value="item"/>
      </el-select>
      <el-input v-model="store.searchText" placeholder="请输入案件相关内容" clearable style="width: 300px; margin-left: 10px" @input="searchData"/>
    </div>
    <el-divider style="width: 98%;margin: 10px 0;"/>
    <div class="lineChart">
      <div v-if="getData || loading" class="content table-container">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="tableData"
          style="width: 100%; height: 100%;"
          class="custom-table"
          :height="400"
          :lazy="true"
          :max-height="400"
          :row-key="(row) => row.id"
          :default-sort="{prop: 'adjudicationTime', order: 'descending'}"
          @scroll="handleScroll"
        >
          <el-table-column label="案件日期" width="130" prop="adjudicationTime" sortable>
            <template #default="scope">
              <div style="display: flex; align-items: center; padding: 8px 0;">
                <el-icon>
                  <timer/>
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.adjudicationTime }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="案件名称" min-width="400" prop="caseName">
            <template #default="scope">
              <el-popover effect="light" trigger="hover" placement="top" width="auto">
                <template #default>
                  <div style="padding: 8px;">
                    <div>相关人员/机构: {{ scope.row.party }}</div>
                    <div>案件内容: {{ scope.row.causeOfAction }}</div>
                  </div>
                </template>
                <template #reference>
                  <el-tag style="margin: 8px 0;">{{ scope.row.caseName }}</el-tag>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center" fixed="right">
            <template #default="scope">
              <div style="display: flex; justify-content: center; align-items: center; padding: 8px 0;">
                <el-popover
                  placement="top"
                  trigger="hover"
                  content="查看案件详情"
                >
                  <template #reference>
                    <el-icon style="margin: 0 8px; cursor: pointer;" color="#409EFF" @click="handleClick(scope.row)">
                      <Document />
                    </el-icon>
                  </template>
                </el-popover>
                <el-icon style="margin: 0 8px; cursor: pointer;" color="#409EFF" @click="handleShowRelatedNodeClick(scope.row)">
                  <Share />
                </el-icon>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 搜索无结果状态 -->
      <div v-else-if="store.searchText !== ''" class="empty-state search-empty">
        <div class="empty-content">
          <el-icon class="empty-icon search-icon"><Search /></el-icon>
          <h3 class="empty-title">未找到相关案件</h3>
          <p class="empty-description">
            没有找到包含 "<span class="search-keyword">{{ store.searchText }}</span>" 的案件信息
          </p>
          <div class="empty-suggestions">
            <div class="suggestion-item">
              <el-icon><EditPen /></el-icon>
              <span>尝试使用不同的关键词</span>
            </div>
            <div class="suggestion-item">
              <el-icon><RefreshLeft /></el-icon>
              <span>清空搜索条件重新查看</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 初始状态 -->
      <div v-else class="empty-state">
        <div class="empty-content">
          <h3 class="empty-title">请选择省份和案件类型</h3>
          <p class="empty-description">选择省份和案件类型后，将显示相应的案件列表</p>
          <div class="empty-suggestions">
            <div class="suggestion-item">
              <el-icon><Location /></el-icon>
              <span>在地图上选择省份</span>
            </div>
            <div class="suggestion-item">
              <el-icon><InfoFilled /></el-icon>
              <span>选择具体的案件类型</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.lawCase {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  position: relative;
  border-radius: 16px;
  backdrop-filter: blur(8px);
  border: 1.5px solid rgba(255, 255, 255, 0.497);
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  width: 54.5vw;
  margin-left: 1.5%;
  padding: 3px;
  box-sizing: border-box;
  height: 98%;
  overflow: hidden;
  transition: all 1s ease;
}

.lineChart {
  height: 70%;
  width: 98%;
  box-sizing: border-box;
  color: #fff;
  border-radius: 12px;
  overflow: hidden;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 3px;

    &:hover {
      background: rgba(255, 255, 255, 0.5);
    }
  }
}

.select {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  width: 98%;
}

.table-container {
  height: 100%;
  width: 100%;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.3);
    border-radius: 3px;

    &:hover {
      background: rgba(0, 0, 0, 0.5);
    }
  }
}

.custom-table {
  :deep(.el-table__header) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
      padding: 12px 0;
    }
  }

  :deep(.el-table__body) {
    td {
      padding: 0;
    }
  }

  :deep(.el-table__row) {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}

// 空状态样式
.empty-state {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.95) 100%);
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
      radial-gradient(circle at 20% 20%, rgba(59, 130, 246, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 80% 80%, rgba(139, 92, 246, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 40% 60%, rgba(16, 185, 129, 0.1) 0%, transparent 50%);
    pointer-events: none;
  }
}

.empty-content {
  text-align: center;
  max-width: 550px;
  padding: 30px 20px;
  position: relative;
  z-index: 1;
}

// 图标样式
.empty-icon-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 20px;

  .main-icon {
    font-size: 48px;
    color: #6366f1;
    position: relative;
    z-index: 2;
  }

  .icon-decoration {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.2) 0%, rgba(139, 92, 246, 0.2) 100%);
    border-radius: 50%;
    animation: pulse-decoration 3s ease-in-out infinite;
  }
}

.search-icon {
  font-size: 56px;
  color: #f59e0b;
  margin-bottom: 16px;
}

.empty-title {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 10px 0;
  background: linear-gradient(135deg, #1f2937 0%, #4f46e5 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.empty-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 24px 0;
  line-height: 1.5;
}

.search-keyword {
  color: #f59e0b;
  font-weight: 600;
  background: rgba(245, 158, 11, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

// 功能网格
.feature-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
  max-width: 500px;
}

.feature-card {
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(229, 231, 235, 0.8);
  border-radius: 10px;
  padding: 16px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  text-align: center;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
    border-color: rgba(99, 102, 241, 0.3);
  }
}

.feature-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 12px auto;

  .el-icon {
    font-size: 20px;
    color: white;
  }
}

.feature-content {
  h4 {
    font-size: 14px;
    font-weight: 600;
    color: #1f2937;
    margin: 0 0 6px 0;
  }

  p {
    font-size: 12px;
    color: #6b7280;
    margin: 0;
    line-height: 1.4;
  }
}

// 搜索建议
.empty-suggestions {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 24px;
  flex-wrap: wrap;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(229, 231, 235, 0.8);
  border-radius: 8px;
  font-size: 14px;
  color: #6b7280;
  transition: all 0.3s ease;

  &:hover {
    background: rgba(245, 158, 11, 0.1);
    border-color: rgba(245, 158, 11, 0.3);
    color: #f59e0b;
  }

  .el-icon {
    font-size: 16px;
    color: #f59e0b;
  }
}

// 快速操作
.quick-actions {
  margin-top: 24px;
}

.action-hint {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(5, 150, 105, 0.1) 100%);
  border: 1px solid rgba(16, 185, 129, 0.2);
  border-radius: 25px;
  font-size: 14px;
  color: #059669;
  font-weight: 500;

  .el-icon {
    font-size: 16px;
    color: #10b981;
  }
}

// 动画效果
@keyframes pulse-decoration {
  0%, 100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.6;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.1);
    opacity: 0.8;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.empty-content {
  animation: fadeInUp 0.6s ease-out;
}

.feature-card {
  animation: fadeInUp 0.6s ease-out;

  &:nth-child(1) { animation-delay: 0.1s; }
  &:nth-child(2) { animation-delay: 0.2s; }
  &:nth-child(3) { animation-delay: 0.3s; }
}

// 响应式设计
@media (max-width: 768px) {
  .feature-grid {
    grid-template-columns: 1fr;
    gap: 12px;
    max-width: 300px;
  }

  .empty-suggestions {
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }

  .empty-title {
    font-size: 18px;
  }

  .empty-description {
    font-size: 13px;
  }

  .empty-content {
    padding: 20px 15px;
    max-width: 400px;
  }
}

@media (max-width: 480px) {
  .feature-grid {
    max-width: 250px;
  }

  .feature-card {
    padding: 12px;
  }

  .feature-icon {
    width: 32px;
    height: 32px;

    .el-icon {
      font-size: 16px;
    }
  }

  .feature-content {
    h4 {
      font-size: 12px;
    }

    p {
      font-size: 11px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  margin-top: 10px;

  :deep(.el-pagination) {
    .el-pager li {
      background: rgba(255, 255, 255, 0.2);
      color: #fff;
      border: 1px solid rgba(255, 255, 255, 0.3);

      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }

      &.is-active {
        background: #409EFF;
        color: #fff;
      }
    }

    .btn-prev, .btn-next {
      background: rgba(255, 255, 255, 0.2);
      color: #fff;
      border: 1px solid rgba(255, 255, 255, 0.3);

      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }

    .el-pagination__total {
      color: #fff;
    }
  }
}
.active {
  /* 保持其他样式不变 */
  height: 60vh;
  width: 60vw;
  transform: translate(-4%, -70%);
  z-index: 999;
  background-color: rgb(0, 0, 0, 0.5);

  /* 新增限制 */
  .el-table {
    max-width: 100vw; /* 或具体数值如 1200px */
    overflow-x: auto;
  }
  span{
    .el-icon{
      transform: rotate(180deg);
    }
  }
}
</style>
